#!/bin/sh
#
# WD APKG service expects these files to be present
#   * preinst.sh
#   * install.sh
#   * init.sh
#   * start.sh
#   * stop.sh
#   * clean.sh
#   * remove.sh
# This installer provides functions for when you remove the extension


INST_LOG="/tmp/${SYNOPKG_PKGNAME}_install.log"
INST_ETC="/var/packages/${SYNOPKG_PKGNAME}/etc"
INST_VARIABLES="${INST_ETC}/installer-variables"
INST_VAR="${SYNOPKG_PKGDEST}/var"

# Optional port forwards file
FWPORTS_FILE="/var/packages/${SYNOPKG_PKGNAME}/conf/${SYNOPKG_PKGNAME}.sc"

TMP_DIR="/shares/Volume_1/.systemfile/${SYNOPKG_PKGNAME}/var"

# Source package specific variable and functions
SVC_SETUP=`dirname $0`"/scripts/service-setup"
if [ -r "${SVC_SETUP}" ]; then
	. "${SVC_SETUP}"
fi

SSS=`dirname $0`"/scripts/start-stop-status"

# Reload wizard variables stored by postinst
if [ -r "${INST_VARIABLES}" ]; then
	. "${INST_VARIABLES}"
fi


# Pre-installation checks
preinst ()
{
	echo "Preinstall ${PKGNAME}"
}

# Install application
install ()
{
	echo "Install ${PKGNAME}"
	TMP=$(readlink -f $1)
	NASPROG=$(readlink -f $2)
	cd ${TMP}
	mkdir target
	tar -C target -xf package.tgz
	rm package.tgz
	mv ${TMP} ${NASPROG}
	if [ -d ${TMP_DIR} ]; then
		echo "Restore ${PKGNAME} backup"
		rm -rf ${SYNOPKG_PKGDEST}/var
		mv ${TMP_DIR} ${SYNOPKG_PKGDEST}
		# TODO: how to upgrade properly?
	fi
}

# Initialize application, setup icon for web ui, setup path
init ()
{
	echo "Init ${PKGNAME}"
	APPDIR=$(readlink -f $1)
	mkdir -p /var/www/${PKGNAME}
	ln -sf ${APPDIR}/web/* /var/www/${PKGNAME}/

	echo "Create user local dir for ${PKGNAME}"
	ln -sf ${SYNOPKG_PKGDEST}/ /usr/local/${PKGNAME}

	# run syno post installation steps
	SYNOPKG_PKG_STATUS="INSTALL"
	service_postinst
}

# Start application binary
start ()
{
	echo "Start ${PKGNAME}"
	${SSS} start
}

# Stop application binary
stop ()
{
	echo "Stop ${PKGNAME}"
	${SSS} stop
}

# Clean up icons and resources to allow volume umount and NAS shutdown
clean ()
{
	echo "Clean ${PKGNAME}"
	APPDIR=$(readlink -f $1)
	rm -rf /var/www/${PKGNAME}

	rm -f /usr/local/${PKGNAME}

	service_postuninst
}

# Backup the config and remove the app
remove ()
{
	echo "Remove ${PKGNAME}"
	APPDIR=$(readlink -f $1)
	echo "but create a backup first"
	rm -rf ${TMP_DIR}
	mkdir -p ${TMP_DIR}
	mv ${SYNOPKG_PKGDEST}/var/* ${TMP_DIR}
	rm -rf ${APPDIR}
}
